package com.xcm.service.impl;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xcm.dao.ProgramDownloadFailureLogMapper;
import com.xcm.dao.ProgramDownloadMapper;
import com.xcm.dao.ProgramInfoMapper;
import com.xcm.dao.ProgramJsonMapper;
import com.xcm.model.TbDeviceInfo;
import com.xcm.model.TbProgramDownload;
import com.xcm.model.TbProgramDownloadFailureLog;
import com.xcm.model.TbProgramJson;
import com.xcm.service.DeviceInfoService;
import com.xcm.service.ProgramDownloadService;

/**
 * 节目下载信息Service实现类
 */
@Service(value = "programDownloadService")
public class ProgramDownloadServiceImpl implements ProgramDownloadService {
	private static Logger logger = LoggerFactory.getLogger(ProgramDownloadServiceImpl.class);
	@Autowired
	private ProgramDownloadMapper programDownloadMapper;
	@Autowired
	private ProgramInfoMapper programInfoMapper;
	@Autowired
	private ProgramJsonMapper programJsonMapper;
	@Autowired
	private ProgramDownloadFailureLogMapper programDownloadFailureLogMapper;
	@Autowired
	private DeviceInfoService deviceInfoService; 
	/**
	 * 保存节目下载信息
	 *
	 * @param programDownload TbProgramDownload对象
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void saveProgramDownload(TbProgramDownload programDownload) {
		programDownloadMapper.saveProgramDownload(programDownload);
	}
	
	/**
	 * 更新节目下载信息
	 *
	 * @param programDownload TbProgramDownload对象
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateProgramDownload(TbProgramDownload programDownload) {
		programDownloadMapper.updateProgramDownload(programDownload);
	}

	/**
	 * 条件查询节目下载状态记录。（只统计数量）
	 */
	@Override
	public long countProgramDownStatus(Integer state, String xcVersion, String mac) {
		return programDownloadMapper.countProgramDownStatus(state,xcVersion,mac);
	}
	
	/**
	 * 根据mac和xcVersion获取下载状态记录
	 * @param mac
	 * @param downloadJson
	 * @return
	 */
	@Override
	public TbProgramDownload getProgramDownloadByMacAndXcVersion(String mac, String downloadJson) {
		return programDownloadMapper.getProgramDownloadByMacAndXcVersion(mac,downloadJson);
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void saveOrUpdateDownload(String mac, String playJson, String downloadJson, Integer state,
			String failureReasonon,String ip) {
		
		TbDeviceInfo deviceInfoByMac = deviceInfoService.getDeviceInfoByMac(mac);
		if ( deviceInfoByMac == null ) {
			logger.error("终端不存在");
			return;
		}
		
		// 验证节目json数据
		TbProgramJson programJsonByXcVersion = programJsonMapper.getProgramJsonByXcVersion(downloadJson);
		if ( programJsonByXcVersion == null ) {
			logger.error("未找到对应的program_json数据");
			return;
		}
		
		// 如果为空就保存，否则，就更新
		TbProgramDownload programDownload = this.getProgramDownloadByMacAndXcVersion(mac,downloadJson);
		if (programDownload == null) {
			programDownload = new TbProgramDownload();
		} 
		programDownload.setDeviceMac(mac);
		programDownload.setPlayJson(playJson);
		programDownload.setDownloadJson(downloadJson);
		programDownload.setUpdateTime(System.currentTimeMillis());
		programDownload.setFailureReasonon(failureReasonon);
		programDownload.setState(state);
		programDownload.setReportIp(ip);
		programDownload.setDeviceHardVer(deviceInfoByMac.getDeviceHardVer());
		programDownload.setDeviceSoftVer(deviceInfoByMac.getDeviceSoftVer());
		programDownload.setDeviceNum(deviceInfoByMac.getDeviceNum());
		programDownload.setDeviceModel(deviceInfoByMac.getDeviceModel());
		programDownload.setGroup(deviceInfoService.queryGroupNamesByCodeRecursively(deviceInfoByMac.getGroupCode()));
		if (programDownload.getProgramDownloadId() == null ) {
			this.saveProgramDownload(programDownload);
		}else {
			this.updateProgramDownload(programDownload);
		}
		
		// 更新program_json表
		upProgramJsonTB(programDownload, programJsonByXcVersion);
		
		// 记录失败日志记录
		if ( programDownload.getState() == 2 ) {
			saveFailureLog(mac, downloadJson,failureReasonon);
		}
		
	}
	
	private void saveFailureLog(String mac, String downloadJson, String failureReasonon) {
		TbProgramDownloadFailureLog log = new TbProgramDownloadFailureLog(mac, downloadJson, new Date().getTime(), failureReasonon);
		programDownloadFailureLogMapper.saveLog(log);
	}

	private void upProgramJsonTB(TbProgramDownload programDownload,TbProgramJson programJsonByXcVersion) {
		if ( programDownload.getState() == 0 ) { // 下载成功
			// TODO 并发下应该加锁，下载成功，更新program_json 下载终端数量+1/判断当前为最后一个终端时更改program_json表的下载成功时间（即最后一个终端下载成功时间）
			Long countDeviceTotal = programInfoMapper.countDeviceTotalByXcVersion(programDownload.getDownloadJson());
			Integer coutDeviceNum = programJsonByXcVersion.getDeviceNum();
			if ( coutDeviceNum == null ) coutDeviceNum = 0;
			if ( coutDeviceNum.intValue() < countDeviceTotal.intValue() ) {
				programJsonByXcVersion.setDeviceNum( coutDeviceNum + 1 );
			} 
			if (programJsonByXcVersion.getDeviceNum() == countDeviceTotal.intValue()) { // 当前为最后一个下载成功终端
				programJsonByXcVersion.setDeviceDownState(0);
				programJsonByXcVersion.setPublishDoneTime(new Date().getTime());
			}
			programJsonMapper.updateProgramJsonAfterDeviceDownload(programJsonByXcVersion);
		} else if ( programDownload.getState() == 2 ) { // 下载失败
			programJsonByXcVersion.setDeviceDownState(2);
			programJsonMapper.updateProgramJsonAfterDeviceDownload(programJsonByXcVersion);
		}
	}
}
